package cn.ronghuanet.auth.service.impl;

import cn.ronghuanet.auth.dto.LoginDTO;
import cn.ronghuanet.auth.mapper.LoginMapper;
import cn.ronghuanet.auth.service.ILoginService;
import cn.ronghuanet.base.util.BaseLoginMap;
import cn.ronghuanet.org.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LoginMapper mapper;

    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {
        // 验证账号或密码是否为null
        if(Objects.isNull(loginDTO)
                || Objects.isNull(loginDTO.getUsername())
                || Objects.isNull(loginDTO.getPassword())){
            throw new RuntimeException("账号或密码未输入!");
        }
        // 调用mapper查询账号是否存在
        Employee user = mapper.selectByName(loginDTO);
        if (Objects.isNull(user)) {
            throw new RuntimeException("账号或密码不正确!");
        }
        // 验证密码是否正确
        if (!user.getPassword().equals(loginDTO.getPassword())){
            throw new RuntimeException("账号或密码不正确!");
        }
        // 为了安全 将密码置为空
        user.setPassword("");
        // 随机数/token/uuid
        String token = UUID.randomUUID().toString();
        // 将登陆用户的数据放入全局的map中去 以后 会使用redis进行替换
        BaseLoginMap.loginMap.put(token,user);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("loginUser",user);
        // 返回
        return map;
    }
}
